package com.ybkj.daijia.config;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.server.errand.ErrandOrderTypeOtherServices;
import com.ybkj.daijia.server.errand.ErrandOrderTypeTips;
import com.ybkj.daijia.server.errand.ErrandPay;
import com.ybkj.daijia.server.errand.Order;
import com.ybkj.daijia.server.errand.OrderUp;
import com.ybkj.daijia.server.errand.OrderUp.PayTypeDetails;
import com.ybkj.daijia.server.model.Driver;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestTemplate;

@Component
public class ErrandUpApi {

    /**
     * 多条件查询跑腿订单
     */

    public static final String QUERY_ERRAND = "api/orders/";
    /**
     * 多条件查询跑腿订单
     */

    public static final String QUERY_ERRAND_UP = "api/orders/up";
    /**
     * 新多条件查询跑腿订单
     */
    public static final String FINDBYPARAMS = "api/orders/up/orderlist";
    /**
     * 根据司机id查询明细
     */
    public static final String DRIVERORDERDETAILVO = "api/orders/up/driverOrderDetailVo";
    public static final String DRIVERORDERDETAILCOUNT = "api/orders/up/driverOrderDetailCount";
    /**
     * 根据名字查询车型.
     */
    public static final String QUERY_BY_TYPENAME = "v2/orderType/findByCompanyIdAndName";
    /**
     * 根据名字查询跑腿类型
     */
    public static final String QUERY_TYPEBY_TYPENAME = "v2/orderTypeUp/findByCompanyIdAndName";
    /**
     * 根据车型id查询车型.
     */
    public static final String QUERY_BY_ID = "v2/orderType/findOrderType";
    /**
     * 根据类型id查询跑腿类型.
     */
    public static final String QUERY_TYPE_BY_ID = "v2/orderTypeUp/findOrderType";
    /**
     * 根据Id查询一个订单
     */
    public static final String QUERY_ONE = "api/orders/up/findOne";
    /**
     * 根据Id查询一个订单
     */
    public static final String QUERY_ONE_UP = "v2/api/orders/up/findOne";
    /**
     * 根据Id查询临时订单
     */
    public static final String QUERY_ONE_TEMP = "v2/api/orders/up/findOneTemp";
    /**
     * 添加订单备注
     */
    public static final String REMARK = "api/orderMemo/up/remark";
    /**
     *
     */
    public static final String REVIEW = "api/orderReview/up";
    /**
     * 查询拒单记录
     */
    public static final String REFUSE = "api/orderRefuse/up/findRefuses";
    /**
     * 创建跑腿订单
     */
    public static final String CREATE = "api/orders/up/";
    /**
     * 修改跑腿订单状态
     */
    public static final String CANCEL = "api/orders/up/update";
    /**
     * 收回订单
     */
    public static final String CALLBACK = "api/orders/up/update";
    public static final String PAIDAN = "api/orders/up/update";
    public static final String PAIDAN_UP = "api/orders/up/update";
    public static final String ONE_ERRAND = "api/orders/up/findOne";
    public static final String COMPLETE_TASK = "api/orders/up/complete";
    /**
     * 查询现有忙碌跑腿订单数量
     */
    public static final String COUNT_BUSY = "api/orders/up/countByEmployId";
    /**
     * 查询催单
     */
    public static final String QUERY_CUIDAN = "api/orders/up/getHastenOrder";
    /**
     * 关闭催单
     */
    public static final String CLOSE_CUIDAN = "api/orders/up/closeHasten";
    /**
     * 查询收费内容
     */
    public static final String FEE_LIST = "api/errandAcKey/findByAppKey";
    /**
     * 新增收费内容
     */
    public static final String ADD_NEW_FEE = "api/errandAcKey/create";
    /**
     * 删除收费内容
     */
    public static final String DELETE_FEE = "api/errandAcKey/delete";
    /**
     * 新增收费内容城市
     */
    public static final String ADD_NEW_FEE_CONTENT = "api/errandPay/create";
    /**
     * 修改收费内容城市
     */
    public static final String UPDATE_FEE_CONTENT = "api/errandPay/update";
    /**
     * 查询单个城市内容
     */
    public static final String ONE_FEE_CONTENT = "api/errandPay/findById";
    /**
     * 删除收费内容城市
     */
    public static final String DELETE_FEE_CONTENT = "api/errandPay/delete";
    /**
     * 跑腿订单汇总
     */
    public static final String COMPOSITIVE = "api/orders/up/chart";
    /**
     * 跑腿订单统计(年)
     */
    public static final String ORDERSTATISTICS = "api/orders/up/errandDataForYear";
    /**
     * 跑腿订单统计(月)
     */
    public static final String ORDERSTATISTICSMONTH = "api/orders/up/errandDataForMonth";
    /**
     * 跑腿订单统计(日)
     */
    public static final String ORDERSTATISTICSDAY = "api/orders/up/errandDataForDay";
    /**
     * 热力图
     */
    public static final String ERRANDHEATMAP = "api/orders/up/errandHeatMap";
    public static final String ERRANDMEMBERORDER = "api/orders/up/errandMemberOrder";
    /**
     * 跑腿订单类型统计
     */
    public static final String ORDERTYPESTATISTICS = "api/orders/up/orderFromSource";
    /**
     * 按时间查询全部公司的跑腿订单统计
     */
    public static final String COMPANYORDERSTATISTICS = "api/orders/up/companyOrder";
    /**
     * 统计服务人员
     */
    public static final String DRIVERACHIEVEMENT = "api/orders/up/driverAchievement";
    /**
     * 查询v2版本的跑腿类型
     */
    public static final String QUERY_ORDER_TYPE = "v2/orderType";
    /**
     * 查询跑腿二期的跑腿类型
     */
    public static final String QUERY_ORDER_TYPE_UP = "v2/orderTypeUp";
    /**
     * 查询V4版本的跑腿类型
     */
    public static final String QUERY_V4_ORDER_TYPE = "v4/api/orders/up/queryTypeV4";
    /**
     * V4版本更新预支付状态
     */
    public static final String UPDATE_IFPAYED = "v4/api/orders/up/updateOrderPayed";
    /**
     * V2查询跑腿类型根据公司名称
     */
    public static final String QUERY_ORDERTYPE_BY_PARAMS = "v2/orderType/findByPage";
    /**
     * V2查询跑腿类型根据类型名称
     */
    public static final String QUERY_ORDERTYPE_BY_TYPENAME = "v2/orderTypeUp/findByPage";
    public static final String SAVE_OPEN_COMPANY = "v2/orderTypeUp/openCompany";
    /**
     * 保存跑腿类型
     */
    public static final String CREATE_ORDER_TYPE = "v2/orderType/create";
    /**
     * 保存跑腿二期类型
     */
    public static final String CREATE_ORDER_TYPE_UP = "v2/orderTypeUp/create";
    /**
     * 修改跑腿类型
     */
    public static final String UPDATE_ORDER_TYPE = "v2/orderType/update/{id}";
    /**
     * 修改跑腿二期类型
     */
    public static final String UPDATE_ORDER_TYPE_UP = "v2/orderTypeUp/update/{id}";
    public static final String COUNT_ORDER_TYPE_UP = "v2/orderTypeUp/countType";
    public static final String DELETE_ORDER_TYPE = "v2/orderType/delete/{typeId}";
    public static final String QUERY_CARTYPECOMPANY = "v2/orderTypeUp/queryErrandTypeCompany";
    public static final String UPDATE_TYPE_COMPANY = "v2/orderTypeUp/updateErrandTypeCompany";
    public static final String DELETE_TYPE_COMPANY = "v2/orderTypeUp/deleteErrandTypeCompany";
    public static final String DELETE_ERRAND_TYPE = "v2/orderTypeUp/delete/{typeId}";
    /**
     * v2跑腿下单
     */
    public static final String SAVEORDER = "v2/api/orders/create";
    /**
     * 跑腿二期后台下单
     */
    public static final String SAVE_ORDER_UP = "v2/api/orders/up/create";
    /**
     * v2跑腿下单
     */
    public static final String SAVE_TEMP_ORDER = "v2/api/orders/up/createTempOrder";
    /**
     * V2查询跑腿订单
     */
    public static final String FINDBYPARAMS_V2 = "v2/api/orders/orderlist";
    /**
     * 查询跑腿二期订单
     */
    public static final String FINDBYPARAMS_UP = "v2/api/orders/up/orderlist";
    /**
     * V2确认跑腿订单
     */
    public static final String CONFIRM_TASK = "v2/api/orders/confirmTask";
    /**
     * 跑腿二期确认跑腿订单
     */
    public static final String CONFIRM_TASK_UP = "v2/api/orders/up/confirmTask";
    /**
     * V2完成跑腿订单
     */
    public static final String FINISH_TASK = "v2/api/orders/up/finishTask";
    /**
     * V2增加网上交易记录
     */
    public static final String CREATE_PAYRECORDORDER = "v2/api/orders/up/createPayRecordOrder";
    /**
     * V2查询网上交易记录
     */
    public static final String QUERY_PAYRECORDORDER_ONE = "v2/api/orders/up/findOnePayRecordOrder";
    /**
     * V2修改网上交易记录
     */
    public static final String TREATMENT_PAYRECORDORDER = "v2/api/orders/up/updatePayRecordOrder";
    /**
     * V2查询跑腿订单
     */
//	public static final String QUERY_ORDER = "v2/api/orders/up";
    public static final String QUERY_ORDER = "v2/api/orders";
    /**
     * V2查询保单数据
     */
    public static final String QUERY_ORDERORBIT = "v2/api/orders/up/findOrderOrbit";
    /**
     * V2修改订单金额
     */
    public static final String UPDATE_REALMONEY = "v2/api/orders/up/updateRealMoney";
    public static final String QUERY_ORDEREVIEW = "api/orderReview/up/findByDriver";
    public static final String QUERY_ORDEREVIEW_ONE = "api/orderReview/up/findOne";
    public static final String DELETE_ORDEREVIEW = "api/orderReview/up/deleteById";
    /**
     * 根据服务人员id分页查询完成订单
     */
    public static final String QUERY_FINISHED_BY_EMPLOY = "v2/api/orders/up/queryFinishOrderByEmployId";
    public static final String COUNT_FINISHED_BY_PASSENGER_DATE = "v2/api/orders/up/countByParam";
    /**
     * 根据passenger查询未支付订单数量
     */
    public static final String COUNT_NOTPAY_BY_PASSENGER = "v2/api/orders/up/countByPassengerId";
    /**
     * 查询服务人员奖励接口
     */
    public static final String FIND_REWARD = "v4/api/orders/up/findOrderByEmployId";
    /**
     * 报销
     */
    public static final String BAOXIAO = "v4/api/orders/up/baoxiao";
    /**
     * 根据客户id查询正在执行的订单数量
     */
    public static final String COUNT_ACTIVED_BY_PASSENGER = "v4/api/orders/up/queryRunOrder";
    /**
     * 根据passenger查询新单、销单、执行中订单数量
     */
    public static final String COUNT_TODAYORDER_BY_PASSENGER = "v2/api/orders/up/countRunning";
    /**
     * 根据客户id查询最近完成订单
     */
    public static final String FIND_LASTEDONE_FINISHED_BY_PASSENGER = "v2/api/orders/up/findLastOrder";
    /**
     * 根据附加服务id查询附加服务
     */
    public static final String FIND_OTHERSERVICE = "v2/orderTypeUp/findOtherService";
    /**
     * 根据热门标签id热门标签
     */
    public static final String FIND_TIPS = "v2/orderTypeUp/findTipsById";
    /**
     * 结算前修改结算时间为当前时间
     */
    public static final String ADD_FINISHTIME = "v2/api/orders/up/prepare";
    /**
     * 更新订单预支付方式、金额等
     */
    public static final String UPDATE_PAYSTATUS = "v4/api/orders/up/updatePayStatus";
    /**
     * 临时订单转换成真实订单
     */
    public static final String TEMP_TO_FOREVER = "v2/api/orders/up/tempToForever";
    private static final Logger logger = LoggerFactory.getLogger(ErrandUpApi.class);
    @Value("${module.errand.url}")
    private String errandBaseURL;
    @Autowired
    private RestTemplate restTemplate;

    public String getErrandBaseURL() {

        return errandBaseURL.endsWith("/") ? errandBaseURL : errandBaseURL + "/";
    }

    public void setErrandBaseURL(String errandBaseURL) {
        this.errandBaseURL = errandBaseURL;
    }

    public RestTemplate getRestTemplate() {
        return restTemplate;
    }

    public void setRestTemplate(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public String get(String apiurl, Map<String, String> kv, Setting setting) {

        kv.put("appKey", setting.getSecKey());

        String result = null;

        try {
            result = restTemplate.getForObject(apiurl, String.class, kv);
        } catch (HttpClientErrorException e) {
            e.printStackTrace();
            logger.error("HttpClientErrorException:code:{},status:{},body:{}", e.getStatusCode(),
                e.getStatusText(), e.getResponseBodyAsString());
            result = e.getResponseBodyAsString();
        } catch (HttpServerErrorException e) {
            e.printStackTrace();
            logger.error("HttpServerErrorException:{}", e.getResponseBodyAsString());
            result = e.getResponseBodyAsString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;

    }

    public String post(String apiurl, Map<String, String> kv, Setting setting) {

        kv.put("appKey", setting.getSecKey());

        String result = null;

        try {
            result = restTemplate.postForObject(apiurl, null, String.class, kv);
        } catch (HttpClientErrorException e) {
            logger.error("HttpClientErrorException:code:{},status:{},body:{}", e.getStatusCode(),
                e.getStatusText(), e.getResponseBodyAsString());
            result = e.getResponseBodyAsString();
        } catch (HttpServerErrorException e) {
            logger.error("HttpServerErrorException:{}", e.getResponseBodyAsString());
            result = e.getResponseBodyAsString();
        }

        return result;
    }

    public String postMultiValueMap(String url, MultiValueMap<String, String> kv, Setting setting) {

        kv.add("appKey", setting.getSecKey());

        Set<Entry<String, List<String>>> entries = kv.entrySet();

        Map<String, String> params = new HashMap<String, String>();
        for (Entry<String, List<String>> entry : entries) {
            List<String> values = entry.getValue();
            params.put(entry.getKey(), CollectionUtils.isEmpty(values) ? null : values.get(0));
        }

        RestTemplate rest = new RestTemplate();

        String result = null;

        try {
            result = rest.postForObject(url, kv, String.class);
        } catch (HttpClientErrorException e) {
            logger.error("HttpClientErrorException:code:{},status:{},body:{}", e.getStatusCode(),
                e.getStatusText(), e.getResponseBodyAsString());
            result = e.getResponseBodyAsString();
        } catch (HttpServerErrorException e) {
            logger.error("HttpServerErrorException:{}", e.getResponseBodyAsString());
            result = e.getResponseBodyAsString();
        }

        return result;
    }

    public String put(String apiurl, Map<String, String> kv, Setting setting) {
        kv.put("appKey", setting.getSecKey());
        String result = null;
        try {
            restTemplate.put(apiurl, null, kv);
        } catch (HttpClientErrorException e) {
            result = e.getResponseBodyAsString();
        }
        return result;

    }

    public String delete(String apiurl, Map<String, String> kv, Setting setting) {

        kv.put("appKey", setting.getSecKey());

        String result = null;

        try {
            restTemplate.delete(apiurl, kv);
        } catch (HttpClientErrorException e) {
            result = e.getResponseBodyAsString();
        }
        return result;

    }

    public Result<OrderUp> findOneOrder(Long orderId, Setting setting) {

        Result<OrderUp> result = new Result<OrderUp>();
        result.setSuccess(false);

        OrderUp order = null;

        StringBuilder sb = new StringBuilder();
        sb.append(
            getErrandBaseURL() + ErrandUpApi.ONE_ERRAND + "?appKey={appKey}&orderId={orderId}");

        Map<String, String> kv = new HashMap<String, String>();
        kv.put("orderId", String.valueOf(orderId));

        String resultStr = get(sb.toString(), kv, setting);

        if (null != resultStr) {
            JSONObject jo = new JSONObject(resultStr);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                order = gson.fromJson(data.toString(), OrderUp.class);
                result.setSuccess(true);
                result.setResult(order);
            } else {
                result.setSuccess(false);
                result.setMessage(jo.getString("message"));
            }
        }

        return result;

    }

    public Result<Order> paidan(Driver driver, Order order, String operator, Setting setting) {

        Result<Order> result = new Result<Order>();
        result.setSuccess(false);

        StringBuilder sb = new StringBuilder();
        Map<String, String> kv = new HashMap<String, String>();

        sb.append(getErrandBaseURL() + ErrandUpApi.PAIDAN + "?appKey={appKey}");

        sb.append("&action={action}");
        sb.append("&orderId={orderId}");
        sb.append("&employId={employId}");
        sb.append("&employName={employName}");
        sb.append("&employPhone={employPhone}");
        sb.append("&employCompanyId={employCompanyId}");
        sb.append("&operator={operator}");

        kv.put("action", String.valueOf("paidan"));
        kv.put("orderId", String.valueOf(order.getId()));
        kv.put("employId", String.valueOf(driver.getId()));
        kv.put("employName", String.valueOf(driver.getRealname()));
        kv.put("employPhone", String.valueOf(driver.getPhone()));
        kv.put("employCompanyId", String.valueOf(driver.getCompanyId()));
        kv.put("operator", String.valueOf(operator));

        String resultStr = put(sb.toString(), kv, setting);

        if (null != resultStr) {
            JSONObject jo = new JSONObject(resultStr);
            String message = jo.getString("message");
            result.setMessage(message);
            result.setSuccess(false);
        } else {
            result.setSuccess(true);
        }

        return result;

    }

    public Result<OrderUp> paidanUp(Driver driver, OrderUp order, String operator,
        Setting setting) {

        Result<OrderUp> result = new Result<OrderUp>();
        result.setSuccess(false);

        StringBuilder sb = new StringBuilder();
        Map<String, String> kv = new HashMap<String, String>();

        sb.append(getErrandBaseURL() + ErrandUpApi.PAIDAN_UP + "?appKey={appKey}");

        sb.append("&action={action}");
        sb.append("&orderId={orderId}");
        sb.append("&employId={employId}");
        sb.append("&employName={employName}");
        sb.append("&employPhone={employPhone}");
        sb.append("&employCompanyId={employCompanyId}");
        sb.append("&operator={operator}");

        kv.put("action", String.valueOf("paidan"));
        kv.put("orderId", String.valueOf(order.getId()));
        kv.put("employId", String.valueOf(driver.getId()));
        kv.put("employName", String.valueOf(driver.getRealname()));
        kv.put("employPhone", String.valueOf(driver.getPhone()));
        kv.put("employCompanyId", String.valueOf(driver.getCompanyId()));
        kv.put("operator", String.valueOf(operator));

        String resultStr = put(sb.toString(), kv, setting);

        if (null != resultStr) {
            JSONObject jo = new JSONObject(resultStr);
            String message = jo.getString("message");
            result.setMessage(message);
            result.setSuccess(false);
        } else {
            result.setSuccess(true);
        }

        return result;

    }

    public Long countBusyAmount(Long employId, Setting setting) {
        Long amount = 0L;
        StringBuilder sb = new StringBuilder();
        sb.append(getErrandBaseURL() + ErrandUpApi.COUNT_BUSY + "?appKey={appKey}");
        sb.append("&employId={employId}");
        Map<String, String> kv = new HashMap<String, String>();

        kv.put("employId", String.valueOf(employId));

        String result = get(sb.toString(), kv, setting);
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                amount = jo.getLong("data");
            }
        }
        return amount;
    }

    public Result<ErrandPay> findOneErrandPay(Long errandPayId, Setting setting) {

        Result<ErrandPay> result = new Result<ErrandPay>();
        result.setSuccess(false);

        ErrandPay errandPay = null;

        StringBuilder sb = new StringBuilder();
        sb.append(getErrandBaseURL() + ErrandUpApi.ONE_FEE_CONTENT
            + "?appKey={appKey}&errandPayId={errandPayId}");

        Map<String, String> kv = new HashMap<String, String>();
        kv.put("errandPayId", String.valueOf(errandPayId));

        String resultStr = get(sb.toString(), kv, setting);

        if (null != resultStr) {
            JSONObject jo = new JSONObject(resultStr);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                errandPay = gson.fromJson(data.toString(), ErrandPay.class);
                result.setSuccess(true);
                result.setResult(errandPay);
            } else {
                result.setSuccess(false);
                result.setMessage(jo.getString("message"));
            }
        }

        return result;

    }

    public Result<Order> completeTask(Order order, Setting setting) {

        Result<Order> result = new Result<Order>();
        result.setSuccess(false);

        StringBuilder sb = new StringBuilder();
        Map<String, String> kv = new HashMap<String, String>();

        sb.append(getErrandBaseURL() + ErrandUpApi.COMPLETE_TASK + "?appKey={appKey}");

        sb.append("&orderId={orderId}");
        sb.append("&cashMoney={cashMoney}");
        sb.append("&signMoney={signMoney}");
        sb.append("&balanceMoney={balanceMoney}");
        sb.append("&mileage={mileage}");
        sb.append("&waitedTime={waitedTime}");
        sb.append("&travelTime={travelTime}");
        sb.append("&payType={payType}");
        sb.append("&shouldPay={shouldPay}");
        sb.append("&realPay={realPay}");
        sb.append("&driverProfit={driverProfit}");
        sb.append("&companyProfit={companyProfit}");

        kv.put("orderId", String.valueOf(order.getId()));
        kv.put("cashMoney", String.valueOf(order.getCashMoney()));
        kv.put("signMoney", String.valueOf(order.getSignMoney()));
        kv.put("balanceMoney", String.valueOf(order.getBalanceMoney()));
        kv.put("mileage", String.valueOf(order.getMileage()));
        kv.put("waitedTime", String.valueOf(order.getWaitedTime()));
        kv.put("travelTime", String.valueOf(order.getTravelTime()));
        kv.put("payType", String.valueOf(order.getPayTypeDetails()));
        kv.put("shouldPay", String.valueOf(order.getShouldPay()));
        kv.put("realPay", String.valueOf(order.getRealPay()));
        kv.put("driverProfit", String.valueOf(order.getDriverProfit()));
        kv.put("companyProfit", String.valueOf(order.getCompanyProfit()));

        String resultStr = post(sb.toString(), kv, setting);

        if (null != resultStr) {
            JSONObject jo = new JSONObject(resultStr);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                Order o = gson.fromJson(data.toString(), Order.class);

                result.setResult(o);
                result.setSuccess(true);
            } else {
                String message = jo.getString("message");
                result.setMessage(message);
                result.setSuccess(false);
            }
        }

        return result;

    }

    public long countFinishedByPassengerAndFinishTime(
        Long passengerId, String orderFromSources, Date startDate, Date endDate, Setting setting) {
        long finishedTimes = 0;

        StringBuilder builder = new StringBuilder();
        builder.append(
            getErrandBaseURL() + ErrandUpApi.COUNT_FINISHED_BY_PASSENGER_DATE + "?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();

        kv.put("passengerId", String.valueOf(passengerId));
        builder.append("&passengerId={passengerId}");

        if (StringUtils.isNotBlank(orderFromSources)) {
            kv.put("orderFromSources", String.valueOf(orderFromSources));
            builder.append("&orderFromSources={orderFromSources}");
        }

        kv.put("startTime", String.valueOf(startDate.getTime()));
        builder.append("&startTime={startTime}");

        if (null != endDate) {
            kv.put("endTime", String.valueOf(endDate.getTime()));
            builder.append("&endTime={endTime}");
        }

        String result = get(builder.toString(), kv, setting);
        if (StringUtils.isNotBlank(result)) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                finishedTimes = jo.getLong("data");
            }
        }
        return finishedTimes;
    }

    public Result<Order> baoxiao(Long orderId, BigDecimal money, Setting setting) {

        Result<Order> vo = new Result<Order>();

        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();

        kv.add("orderId", String.valueOf(orderId));
        kv.add("baoxiaoMoney", String.valueOf(money));

        String result = postMultiValueMap(getErrandBaseURL() + ErrandUpApi.BAOXIAO, kv, setting);

        if (StringUtils.isNotBlank(result)) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                vo.setSuccess(true);
            } else {
                String message = jo.getString("message");
                vo.setMessage(message);
            }
        } else {
            vo.setMessage("内部服务器错误");
        }

        return vo;

    }

    public long countActiveByPassenger(Long passengerId, Setting setting) {
        long activedTimes = 0;

        StringBuilder builder = new StringBuilder();
        builder.append(
            getErrandBaseURL() + ErrandUpApi.COUNT_ACTIVED_BY_PASSENGER + "?appKey={appKey}");

        Map<String, String> kv = new HashMap<String, String>();

        kv.put("passengerId", String.valueOf(passengerId));
        builder.append("&passengerId={passengerId}");

        String result = get(builder.toString(), kv, setting);
        if (StringUtils.isNotBlank(result)) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                activedTimes = jo.getLong("data");
            }
        }
        return activedTimes;
    }

    public long countTodayOrderByPassenger(Long passengerId, Setting setting) {
        long todayOrder = 0;

        StringBuilder builder = new StringBuilder();
        builder.append(
            getErrandBaseURL() + ErrandUpApi.COUNT_TODAYORDER_BY_PASSENGER + "?appKey={appKey}");

        Map<String, String> kv = new HashMap<String, String>();

        kv.put("passengerId", String.valueOf(passengerId));
        builder.append("&passengerId={passengerId}");

        String result = get(builder.toString(), kv, setting);
        if (StringUtils.isNotBlank(result)) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                todayOrder = jo.getLong("data");
            }
        }
        return todayOrder;
    }

    public Result<Order> selectLastedOneFinishedByPassenger(Long passengerId, Setting setting) {

        Result<Order> result = new Result<Order>();
        result.setSuccess(false);

        Order order = null;

        StringBuilder builder = new StringBuilder();
        builder.append(getErrandBaseURL() + ErrandUpApi.FIND_LASTEDONE_FINISHED_BY_PASSENGER
            + "?passengerId={passengerId}&appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("passengerId", String.valueOf(passengerId));
        String resultStr = get(builder.toString(), kv, setting);

        if (null != resultStr) {
            JSONObject jo = new JSONObject(resultStr);
            Integer code = jo.getInt("code");
            if (code == 0) {
                Object object = jo.get("data");
                if (null != object && !object.toString().equals("null")) {
                    JSONObject data = jo.getJSONObject("data");
                    Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                    order = gson.fromJson(data.toString(), Order.class);
                    result.setResult(order);
                }
                result.setSuccess(true);
            } else {
                result.setSuccess(false);
                result.setMessage(jo.getString("message"));
            }
        }
        return result;
    }


    public Result<Order> addFinishTime(Long orderId, Setting setting) {

        Result<Order> vo = new Result<Order>();

        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();

        kv.add("orderId", String.valueOf(orderId));

        String result = postMultiValueMap(getErrandBaseURL() + ErrandUpApi.ADD_FINISHTIME, kv,
            setting);

        if (StringUtils.isNotBlank(result)) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                Boolean data = jo.getBoolean("data");
                vo.setSuccess(data);
                return vo;
            } else {
                String message = jo.getString("message");
                vo.setMessage(message);
            }
        } else {
            vo.setMessage("内部服务器错误");
        }

        return vo;

    }

    public Result<OrderUp> updatePayStatus(Long id, PayTypeDetails prePayType,
        BigDecimal shouldPayMoney, BigDecimal couponMoney, Setting setting) {
        Result<OrderUp> vo = new Result<OrderUp>();

        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();

        kv.add("id", String.valueOf(id));
        kv.add("prePayType", prePayType.toString());
        kv.add("shouldPayMoney", shouldPayMoney.toString());
        kv.add("couponMoney", couponMoney.toString());

        String result = postMultiValueMap(getErrandBaseURL() + ErrandUpApi.UPDATE_PAYSTATUS, kv,
            setting);

        if (StringUtils.isNotBlank(result)) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                Boolean data = jo.getBoolean("data");
                vo.setSuccess(data);
                return vo;
            } else {
                String message = jo.getString("message");
                vo.setMessage(message);
            }
        } else {
            vo.setMessage("内部服务器错误");
        }

        return vo;
    }

    public ErrandOrderTypeOtherServices getOtherServiceById(String id,
        Setting setting) {
        ErrandOrderTypeOtherServices vo = new ErrandOrderTypeOtherServices();
        StringBuilder builder = new StringBuilder();
        builder.append(
            getErrandBaseURL() + ErrandUpApi.FIND_OTHERSERVICE + "?id={id}&appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("id", String.valueOf(id));
        String resultStr = get(builder.toString(), kv, setting);

        if (null != resultStr) {
            JSONObject jo = new JSONObject(resultStr);
            Integer code = jo.getInt("code");
            if (code == 0) {
                Object object = jo.get("data");
                if (null != object && !object.toString().equals("null")) {
                    JSONObject data = jo.getJSONObject("data");
                    Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                    vo = gson.fromJson(data.toString(), ErrandOrderTypeOtherServices.class);
                }
            }
        }
        return vo;
    }

    public ErrandOrderTypeTips getTipsById(String id, Setting setting) {
        ErrandOrderTypeTips vo = new ErrandOrderTypeTips();
        StringBuilder builder = new StringBuilder();
        builder.append(getErrandBaseURL() + ErrandUpApi.FIND_TIPS + "?id={id}&appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("id", String.valueOf(id));
        String resultStr = get(builder.toString(), kv, setting);

        if (null != resultStr) {
            JSONObject jo = new JSONObject(resultStr);
            Integer code = jo.getInt("code");
            if (code == 0) {
                Object object = jo.get("data");
                if (null != object && !object.toString().equals("null")) {
                    JSONObject data = jo.getJSONObject("data");
                    Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                    vo = gson.fromJson(data.toString(), ErrandOrderTypeTips.class);
                }
            }
        }
        return vo;
    }

    public Result<OrderUp> completeUpTask(OrderUp order, Setting setting) {

        Result<OrderUp> result = new Result<OrderUp>();
        result.setSuccess(false);

        StringBuilder sb = new StringBuilder();
        Map<String, String> kv = new HashMap<String, String>();

        sb.append(getErrandBaseURL() + ErrandUpApi.COMPLETE_TASK + "?appKey={appKey}");

        sb.append("&orderId={orderId}");
        sb.append("&cashMoney={cashMoney}");
        sb.append("&signMoney={signMoney}");
        sb.append("&balanceMoney={balanceMoney}");
        sb.append("&mileage={mileage}");
        sb.append("&waitedTime={waitedTime}");
        sb.append("&travelTime={travelTime}");
        sb.append("&payType={payType}");
        sb.append("&shouldPay={shouldPay}");
        sb.append("&realPay={realPay}");
        sb.append("&driverProfit={driverProfit}");
        sb.append("&companyProfit={companyProfit}");

        kv.put("orderId", String.valueOf(order.getId()));
        kv.put("cashMoney", String.valueOf(order.getCashMoney()));
        kv.put("signMoney", String.valueOf(order.getSignMoney()));
        kv.put("balanceMoney", String.valueOf(order.getBalanceMoney()));
        kv.put("mileage", String.valueOf(order.getMileage()));
        kv.put("waitedTime", String.valueOf(order.getWaitedTime()));
        kv.put("travelTime", String.valueOf(order.getTravelTime()));
        kv.put("payType", String.valueOf(order.getPayTypeDetails()));
        kv.put("shouldPay", String.valueOf(order.getShouldPay()));
        kv.put("realPay", String.valueOf(order.getRealPay()));
        kv.put("driverProfit", String.valueOf(order.getDriverProfit()));
        kv.put("companyProfit", String.valueOf(order.getCompanyProfit()));

        String resultStr = post(sb.toString(), kv, setting);

        if (null != resultStr) {
            JSONObject jo = new JSONObject(resultStr);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                OrderUp o = gson.fromJson(data.toString(), OrderUp.class);

                result.setResult(o);
                result.setSuccess(true);
            } else {
                String message = jo.getString("message");
                result.setMessage(message);
                result.setSuccess(false);
            }
        }

        return result;

    }
}
